package com.gwtprocessingjs.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * This class demonstrates dynamic addition and removal of canvases that
 * render Processing script.
 */
public class AddPdeCanvas implements EntryPoint {
	
	// UI Elements.
	private final FlowPanel back = new FlowPanel();
	private final Button addButton = new Button("Add Canvas");
	private final Button removeButton = new Button("Remove Canvas");
	
	// Container for all canvases.
	private final List<Widget> canvasList = new ArrayList<Widget>();
	
	// Integer that will uniquely identify each canvas.
	private static int canvasId = 0;
	
	@Override
	public void onModuleLoad() {
		back.add(new Label("Creating a processing canvas dynamically via GWT"));	
		back.add(addButton);
		back.add(removeButton);
		RootPanel.get("gwt").add(back);
		
		addButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				addCanvas();
			}
		});
		
		removeButton.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				removeCanvas();
			}
		});
	}
	
	/**
	 * Initialize Processing and attach it to the canvas element
	 * in the HTML by Id. 
	 * @param canvasElementId id of the canvas to be created
	 */
	private native void initializeCanvas(String canvasElementId) /*-{
		$wnd.initializeCanvas(canvasElementId);
	}-*/;
	
	// --- Private Methods ---
	
	/** Adds a new canvas and increments the static canvasId int. */
	private void addCanvas() {
		if (canvasList.size() >= 5) {
			return;
		}
		String id = "AddCanvas_" + canvasId++;
		HTML canvasElement = new HTML("<canvas id=\"" + id + "\"/>");
		back.add(canvasElement);
		canvasList.add(canvasElement);
		initializeCanvas(id);
	}
	
	/** Removes the last canvas in the canvasList. */
	private void removeCanvas() {
		if (canvasList.size() == 0) {
			return;
		}
		Widget toRemove = canvasList.get(canvasList.size() - 1);
		canvasList.remove(toRemove);
		back.remove(toRemove);
	}
}
